package com.ygqh.baby.controller.mobile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.ygqh.baby.ao.*;
import com.ygqh.baby.model.*;
import com.ygqh.baby.po.YgProduct;
import com.ygqh.baby.po.YgSearchWords;
import com.ygqh.baby.po.YgSku;
import com.ygqh.baby.redis.RedisDao;
import com.ygqh.baby.service.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 商品类
 *
 * @author ZhangSai
 */
@Controller
@RequestMapping("/mobile/product")
public class YgProductController extends BaseController {

    @Autowired
    private YgProductService ygProductService;
    @Autowired
    private YgSkuService ygSkuService;
    @Autowired
    private YgBrandService brandService;
    @Autowired
    private YgSearchKeywordsService ygSearchKeywordsService;
    @Autowired
    private YgProductRecommendService ygProductRecommendService;
    @Autowired
    private RedisDao redisDao;
    @Autowired
    private YgStockService ygStockService;
    @Autowired
    private YgSearchWordsService ygSearchWordsService;

    /**
     * 商品详情页
     *
     * @param callback
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject detail(@RequestParam String callback, @RequestParam Long id) throws Exception {
        YgProductModel product = ygProductService.findDetailModel(id);
        return new JSONPObject(callback, Message.success(product));
    }

    @RequestMapping(value = "/findSku", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject findSku(@RequestParam String callback, @RequestParam Long productId) throws Exception {
        List<YgSkuModel> skuList = ygProductService.findSku(productId);
        return new JSONPObject(callback, Message.success(skuList));
    }

    @RequestMapping(value = "/detailV2", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject detailV2(@RequestParam String callback, @RequestParam Long id) throws Exception {
        YgProductModel product = ygProductService.findDetailModelV2(id);
        return new JSONPObject(callback, Message.success(product));
    }

    @RequestMapping(value = "/selectProductByGroup", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject selectProductByGroup(@RequestParam String callback, @RequestParam Long groupId) throws Exception {
        List<YgProductModel> products = ygProductService.findDetailModelByGroup(groupId);
        return new JSONPObject(callback, Message.success(products));
    }

    @RequestMapping(value = "/selectProductByGroupId", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject selectProductByGroupId(@RequestParam String callback, @RequestParam Long groupId) throws Exception {
        List<Map<String, Object>> products = ygProductService.findProductByGroupId(0L, groupId);

        return new JSONPObject(callback, Message.success(products));
    }

    @RequestMapping(value = "/findSkuByProductCode", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject findSkuByProductCode(@RequestParam(required = true) String callback, @RequestParam(required = true) Long productId) throws Exception {
        List<YgSku> skus = ygSkuService.find(productId);
        return new JSONPObject(callback, skus);
    }

    /**
     * 相似商品
     *
     * @param callback
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/similarityProduct", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject similarityProduct(@RequestParam(required = true) String brandName, @RequestParam(required = true) Long categoryId,
                                         @RequestParam(required = true) String callback) throws Exception {
        List<YgSimilarProductModel> result = ygProductService.findSimilarityProduct(brandName, categoryId);
        return new JSONPObject(callback, Message.success(result));
    }

    /**
     * 根据用户id查询购买过的商品
     *
     * @param callback
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/findProduct4ShaidanModel", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject findProduct4ShaidanModel(QueryInfo queryInfo, @RequestParam(required = true) String callback) throws Exception {
        // ResultSet<YgProduct4ShaidanModel> result =
        // ygProductService.findProduct4ShaidanModel(queryInfo,SessionUtil.getCurrentUser().getId());
        ResultSet<YgProduct4ShaidanModel> result = ygProductService.findProductAllModel(queryInfo);
        return new JSONPObject(callback, Message.success(result.getResult()));
    }

    /**
     * 商品列表页
     *
     * @param param 参数
     * @return JSONPObject
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject list(ProductListRequestParam param) {
        param.setSalesPlatform(SalesPlatform.Yiigoo.name());
        param.setSaleStatus(ProductStatus.OnSale);
        List<YgProduct4ListModel> result = ygProductService.findList(param);
        return new JSONPObject(param.getCallback(), Message.success(result));
    }

    /**
     * 商品列表页
     *
     * @param callback
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/listByPack", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject listByPack(QueryInfo queryInfo, @RequestParam(required = true) String callback, String sortKey, String dir, Long packId)
            throws Exception {
        if (!StringUtils.isBlank(sortKey)) {
            queryInfo.setSortKey(sortKey);
        }
        if (!StringUtils.isBlank(dir)) {
            queryInfo.setOrderByClause(dir);
        }
        ResultSet<YgProduct4ListModel> result = ygProductService.findListByPack(queryInfo, packId);
        return new JSONPObject(callback, Message.success(result.getResult()));
    }

    /**
     * 商品列表页
     *
     * @param callback
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/listByBmdism", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject listByBmdism(QueryInfo queryInfo, @RequestParam(required = true) String callback, String sortKey, String dir, Long bmdismId)
            throws Exception {
        if (!StringUtils.isBlank(sortKey)) {
            queryInfo.setSortKey(sortKey);
        }
        if (!StringUtils.isBlank(dir)) {
            queryInfo.setOrderByClause(dir);
        }
        ResultSet<YgProduct4ListModel> result = ygProductService.findListByBmdism(queryInfo, bmdismId);
        return new JSONPObject(callback, Message.success(result.getResult()));
    }

    /**
     * 是否是自营品牌
     *
     * @param callback
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/isSelfBrand", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject isSelfBrand(QueryInfo queryInfo, @RequestParam(required = true) String callback, @RequestParam(required = true) String brandName)
            throws Exception {

        Boolean b = brandService.isSelfBrand(brandName);
        return new JSONPObject(callback, Message.success(b));
    }

    @RequestMapping(value = "/getSearchKeywords", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject getSearchKeywords(@RequestParam(required = true) String callback) {
        Map<String, List<String>> searchKeywords = ygSearchKeywordsService.findSearchKeywords();

        return new JSONPObject(callback, Message.success(searchKeywords));
    }

    /**
     * 获取款式的推荐商品
     *
     * @param groupId   款式id
     * @param productId 当前详情页的商品id
     * @param callback
     * @return
     */
    @RequestMapping("/getProductRecommend")
    @ResponseBody
    public JSONPObject getProductRecommend(@RequestParam(required = true) Long groupId, Long productId, @RequestParam(required = true) String callback,
                                           QueryInfo queryInfo) {
        List<YgProductRecommendModel> list = ygProductRecommendService.findProductByGroupId(queryInfo, groupId);
        if (productId != null) {
            List<YgProductRecommendModel> list2 = list.stream().filter(o -> o.getId().compareTo(productId) != 0).collect(Collectors.toList());
            return new JSONPObject(callback, Message.success(list2));
        }
        return new JSONPObject(callback, Message.success(list));
    }

    @RequestMapping("/getProductBySkuId")
    @ResponseBody
    public JSONPObject getProductBySkuId(@RequestParam(required = true) String skuCode, @RequestParam(required = true) Long productId,
                                         @RequestParam(required = true) String callback) {
        Map<String, Object> ygProduct = ygProductService.selectProductBySkuId(skuCode, productId);
        return new JSONPObject(callback, Message.success(ygProduct));
    }

    @RequestMapping("/getProductListBySupplierId")
    @ResponseBody
    public JSONPObject getProductListBySupplierId(@RequestParam(required = true) Long supplierId, @RequestParam(required = true) String callback) {
        List<Map<String, Object>> ygProduct = ygProductService.findProductListBySupplierId(supplierId);
        return new JSONPObject(callback, Message.success(ygProduct));
    }

    /**
     * 商品列表页
     *
     * @param callback
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getPreDateProduct", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject getPreDateProduct(QueryInfo queryInfo, @RequestParam(required = true) String callback, String sortKey, String dir, Long packId) {
        List<YgProduct> result = ygProductService.find(queryInfo, null, null, ProductStatus.OnSale.name(), 1L, true);
        return new JSONPObject(callback, Message.success(result));
    }

    @RequestMapping(value = "/getVipProduct", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject getVipProduct(@RequestParam(required = true) String callback) {
        String string = redisDao.get("vipskuinfo");
        Map<String, Object> map = new HashMap<String, Object>();

        List<YgSkuInfo> list = JSON.parseObject(string, new TypeReference<List<YgSkuInfo>>() {
        });

        if (list != null) {
            map.put("skuList", list);
        }

        String str = redisDao.get("vipprice");
        Map<String, Object> pricemap = JSONObject.parseObject(str, Map.class);
        if (pricemap != null) {
            map.put("sourceVipPrice", pricemap.get("sourceVipPrice"));
            map.put("vipPrice", pricemap.get("vipPrice"));
        }
        return new JSONPObject(callback, Message.success(map));

    }

    @RequestMapping(value = "/getStockByProductCode", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject getStockByProductCode(String productCode, @RequestParam(required = true) String callback) {
        List<YgStockModel> list = ygStockService.findByProductCode(productCode);
        return new JSONPObject(callback, Message.success(list));
    }

    @RequestMapping("getSkuMatchInfoByProductIds")
    @ResponseBody
    public JSONPObject getSkuMatchInfoByProductIds(String[] productIds, String callback) {
        return new JSONPObject(callback, Message.success(ygSkuService.getSkuMatchInfoByProductIds(productIds)));
    }

    /**
     * 推荐拼团商品
     *
     * @param callback      callback
     * @param salesPlatform 销售平台（必传）
     * @return
     */
    @RequestMapping("groupProductForRecommend")
    @ResponseBody
    public JSONPObject groupProductForRecommend(@RequestParam String salesPlatform, @RequestParam String callback,
                                                @RequestParam(defaultValue = "false") Boolean skipYg) {
        return new JSONPObject(callback, Message.success(
                ygProductService.productListByGroupOrder(new QueryInfo(12), salesPlatform, "拼团推荐", skipYg)));
    }

    /**
     * 指定销售属性的拼团列表
     *
     * @param queryInfo     分页
     * @param tags          销售属性
     * @param salesPlatform 销售平台（必传）
     * @param callback      callback
     * @return
     */
    @RequestMapping("groupProductByTags")
    @ResponseBody
    public JSONPObject groupProductByTags(QueryInfo queryInfo, String tags, @RequestParam String salesPlatform,
                                          @RequestParam String callback,
                                          @RequestParam(defaultValue = "false") Boolean skipYg) {
        return new JSONPObject(callback, Message.success(
                ygProductService.productListByGroupOrder(queryInfo, salesPlatform, tags, skipYg)));
    }

    /**
     * 搜索词提示
     *
     * @param callback
     * @param words
     * @return
     */
    @RequestMapping("searchwords")
    @ResponseBody
    public JSONPObject searchwords(String callback, String words) {
        List<String> list = ygSearchWordsService.findValidWords(words, 10);
        return new JSONPObject(callback, Message.success(list));
    }

    /**
     * 记录搜索词
     *
     * @param callback
     * @param words
     * @return
     */
    @RequestMapping("saveSerachWords")
    @ResponseBody
    public JSONPObject saveSerachWords(String callback, String words) {
        ygSearchWordsService.addAsync(new YgSearchWords(words, null, null));
        return new JSONPObject(callback, Message.success(null));
    }
}
